package com.lxq.opengltest02.Util;

import android.content.Context;
import android.opengl.GLES20;
import android.util.Log;

import com.lxq.opengltest02.R;

/**
 * 作者： lxq on 2017/7/10 11:10
 * 邮箱： 842202389@qq.com
 * 用途：
 */

public class ShaderUtil {
    public static int getProgramId(Context context) {
        String vertexStr = TextReaderUtil.readTextFromResource(context, R.raw.simple_vertex_shader);

        int vertexId = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
        GLES20.glShaderSource(vertexId, vertexStr);
        GLES20.glCompileShader(vertexId);

        int[] compile = new int[1];
        GLES20.glGetShaderiv(vertexId, GLES20.GL_COMPILE_STATUS, compile, 0);
        if (compile[0] == 0) {
            GLES20.glDeleteShader(vertexId);
            Log.e("opengl", "compile program failed");
        }

        String fragStr = TextReaderUtil.readTextFromResource(context, R.raw.simple_fragment_shader);
        int fragId = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
        GLES20.glShaderSource(fragId, fragStr);
        GLES20.glCompileShader(fragId);
        int[] compile1 = new int[1];
        GLES20.glGetShaderiv(fragId, GLES20.GL_COMPILE_STATUS, compile1, 0);
        if (compile1[0] == 0) {
            GLES20.glDeleteShader(fragId);
            Log.e("opengl", "compile program failed");
        }


        int program = GLES20.glCreateProgram();
        GLES20.glAttachShader(program, vertexId);
        GLES20.glAttachShader(program, fragId);
        GLES20.glLinkProgram(program);
        int[] compile2 = new int[1];
        GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, compile2, 0);
        if (compile2[0] == 0) {
            GLES20.glDeleteProgram(program);
            Log.e("opengl", "Linking of program failed");
        }
        return program;
    }
}
